package com.aracky.common.util.wxutil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aracky.common.exception.BaseException;
import com.aracky.common.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zengzhiping
 * @ClassName: AuthToken
 * @Description: 获取token信息
 * @date 2021/11/8 16:50
 */
@Component
@Slf4j
public class AuthTokenUtil {


    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${wx.config.corpid}")
    private String corpId;

    @Value("${wx.config.secret}")
    private String secret;

    /**
     * 获取正常token
     *
     * @return
     */
    public String getAccessToken() {
        return send();
    }

    /**
     * 获取同步通讯录token
     * mailListSecret
     *
     * @return
     */
    public String getMailListAccessToken() {
        return send();
    }

    private String send() {
        String accessToken;
        try {
            //根据APPSECRET_KEY从缓存中取accessToken，为null则从企业微信接口取
            accessToken = (String) redisTemplate.opsForValue().get(corpId + secret);
            if (StringUtils.isNotBlank(accessToken)) {
                return accessToken;
            }
            //构造url和参数
            String wxUrl = WxUrl.ACCESS_TOKEN_URL;
            Map<String, Object> param = new HashMap<>();
            param.put("corpid", corpId);
            param.put("corpsecret", secret);
            //访问接口
            String body = HttpUtil.sendGetHttps(wxUrl, param);
            JSONObject result = JSON.parseObject(body);
            log.info("=================企业微信获取token结果：" + result.toJSONString());
            if (0 == result.getInteger("errcode")) {
                accessToken = result.getString("access_token");
                redisTemplate.opsForValue().set(corpId + secret, accessToken, 7100, TimeUnit.SECONDS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("企业微信获取accessToken失败...");
        }
        return accessToken;
    }

}
